﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Aj.Core.Control;
using System.Web.UI;
using System.Text;
using System.Collections;
using System.Xml;
using Aj.Core;

public static class Utility
{
    private static readonly object LockHelper = new object();

    public static int ArticleCid = 62;                               //新闻大类ID
    public static int NewsCid = 64;                                  //新闻ID
    public static int VodeoCid = 65;                                 //视频ID
    public static int WorkNewsPicCid = 66;                           //工作、生活环境ID
    public static int VisitCid = 68;                                 //领导来访

    public static int AboutCid = 69;                                 //关于日发
    public static int IndustryCid = 70;                              //日发产业
    public static int RfsocietyCid = 71;                             //日发与社
    public static int JoinCid = 86;                                  //加入日发

    public static int PhotoCid = 63;                                 //图片大类ID
    public static int ActivityPicCid = 67;                           //员工活动ID
    public static int PhotoHonorPicCid = 91;                         //日发荣誉

    public static string SiteUrl = "SiteUrl";                        //网站地址
    public static string SiteName = "SiteName";                      //网站名字
    public static string SuperuserName = "SuperuserName";            //管理员名
    public static string SuperuserPwd = "SuperuserPwd";              //管理员密码
    public static string NewsImg = "NewsImg";                        //图片上传目录

    public static string PatternInt = "^[0-9]*[1-9][0-9]*$";         //正整数 

    /// <summary>
    /// 返回appSettings值
    /// </summary>
    /// <param name="key">键</param>
    /// <returns></returns>
    public static string Setting(string key)
    {
        return ConfigurationManager.AppSettings[key]; ;
    }

    #region [ 检测验证 ]

    /// <summary>
    /// 检测格式
    /// </summary>
    /// <param name="str">要判断的email字符串</param>
    /// <param name="pattern"></param>
    /// <returns>判断结果</returns>
    public static bool IsValidForRegex(string str, string pattern)
    {
        return Regex.IsMatch(str, pattern);
    }

    /// <summary>
    /// 分析用户请求是否正常
    /// </summary>
    /// <param name="Str">传入用户提交数据</param>
    /// <returns>返回是否含有SQL注入式攻击代码</returns>
    public static bool ProcessSqlStr(string Str)
    {
        bool ReturnValue = true;
        try
        {
            if (Str != "" && Str != null)
            {
                string SqlStr = "'|*|--|;|";
                SqlStr += "and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare";
                string[] anySqlStr = SqlStr.Split('|');
                foreach (string ss in anySqlStr)
                {
                    if (Str.IndexOf(ss) >= 0)
                    {
                        ReturnValue = false;
                    }
                }
            }
        }
        catch
        {
            ReturnValue = false;
        }
        return ReturnValue;
    }

    /// <summary>
    /// 是否为ip
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool IsIP(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    #endregion

    #region [ 加密解密 ]

    /// <summary>
    /// 加密(SHA1)
    /// </summary>
    /// <param name="password"></param>
    /// <returns></returns>
    public static string Encrypt(string password)
    {
        if (string.IsNullOrEmpty(password))
            return string.Empty;
        return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
    }

    /// <summary>
    /// 加密(MD5)
    /// </summary>
    /// <param name="password"></param>
    /// <returns></returns>
    public static string EncryptToMd5(string password)
    {
        if (string.IsNullOrEmpty(password))
            return string.Empty;
        return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
    }

    #endregion

    #region [ 获取IP地址 ]

    /// <summary>
    /// 获取IP地址
    /// </summary>
    /// <returns></returns>
    public static string GetIP()
    {
        string ip = string.Empty;
        if (null != HttpContext.Current.Request)
        {
            ip = HttpContext.Current.Request.UserHostAddress;
            if (HttpContext.Current.Request.ServerVariables != null)
            {
                foreach (string k in HttpContext.Current.Request.ServerVariables.AllKeys)
                {
                    if (k != "REMOTE_ADDR")
                        continue;
                    else
                    {
                        ip = HttpContext.Current.Request.ServerVariables[k];
                        break;
                    }
                }
            }
            if (ip == null) ip = string.Empty;
        }
        return ip;
    }

    //获取本机的IP
    public static string getLocalIP()
    {
        string strAddr = GetIP();
        if (strAddr == "::1")
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
            if (ipEntry != null)
                strAddr = ipEntry.AddressList[0].ToString();
        }
        return (strAddr);
    }

    /// <summary>
    /// 获得当前页面客户端的IP
    /// </summary>
    /// <returns>当前页面客户端的IP</returns>
    public static string GetIP2()
    {
        string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(result) || !IsIP(result))
            return "127.0.0.1";

        return result;
    }

    #endregion

    #region [ 操作字符串 ]

    /// <summary>
    /// 获取字符串中指定位置开始的指定长度的字符串，支持汉字英文混合 汉字为2字节计数
    /// </summary>
    /// <param name="strSub">输入中英混合字符串</param>
    /// <param name="start">开始截取的起始位置</param>
    /// <param name="length">要截取的字符串长度（字节数）</param>
    /// <returns></returns>
    public static string GetSubString(string _str, int _start, int _length)
    {
        if (string.IsNullOrEmpty(_str))
            return null;

        string temp = _str;
        int j = 0, k = 0, p = 0;

        CharEnumerator ce = temp.GetEnumerator();
        while (ce.MoveNext())
        {
            j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2;

            if (j <= _start)
            {
                p++;
            }
            else
            {
                if (j == GetLength(temp))
                {
                    temp = temp.Substring(p, k + 1);
                    break;
                }
                if (j <= _length + _start)
                {
                    k++;
                }
                else
                {
                    temp = temp.Substring(p, k);
                    break;
                }
            }
        }

        return temp;
    }

    /// <summary>
    /// 获取指定字符串长度，汉字以2字节计算
    /// </summary>
    /// <param name="aOrgStr">要统计的字符串</param>
    /// <returns></returns>
    public static int GetLength(String aOrgStr)
    {
        if (string.IsNullOrEmpty(aOrgStr)) return 0;
        int intLen = aOrgStr.Length;
        int i;
        char[] chars = aOrgStr.ToCharArray();
        for (i = 0; i < chars.Length; i++)
        {
            if (System.Convert.ToInt32(chars[i]) > 255)
            {
                intLen++;
            }
        }
        return intLen;
    }

    /// <summary>
    /// 返回链接地址
    /// </summary>
    /// <param name="_href"></param>
    /// <param name="_link"></param>
    /// <returns></returns>
    public static string GetHref(string _href, string _link)
    {
        return string.IsNullOrEmpty(_href) ? _link : _href;
    }

    public static string Trim(string str)
    {
        return (str == null) ? string.Empty : str.Trim();
    }

    /// <summary>
    /// 转换成字符串型，如果传进来的参数为null,返回空字符串
    /// </summary>
    /// <param name="obj"></param>
    public static string ToString(object obj)
    {
        return IsNullOrDBNull(obj) ? string.Empty : Convert.ToString(obj);
    }

    public static bool IsNullOrDBNull(object o)
    {
        return o == null || Convert.IsDBNull(o);
    }

    /// <summary>
    /// 字符串转换成double
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static double StringTodouble(string str)
    {
        double decimalMoney;
        if (double.TryParse(str, out decimalMoney))
        {
            return decimalMoney;
        }
        return 0;
    }

    /// <summary>
    /// 判断字符串是否相同（忽略大小写）
    /// </summary>
    /// <param name="str1"></param>
    /// <param name="str2"></param>
    /// <returns></returns>
    public static bool EqualsIgnoreCase(String str1, String str2)
    {
        return String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// 去除 HTML tag  google "StripHTML" 得到
    /// </summary>
    /// <param name="HTML">源</param>
    /// <returns>结果</returns>
    public static string StripHTML(string HTML)
    {
        string[] Regexs ={
                                    @"([\r\n])[\s]+",
                                    @"&(quot|#34);",
                                    @"&(amp|#38);",
                                    @"&(lt|#60);",
                                    @"&(gt|#62);",
                                    @"&(nbsp|#160);",
                                    @"&(iexcl|#161);",
                                    @"&(cent|#162);",
                                    @"&(pound|#163);",
                                    @"&(copy|#169);",
                                    @"&#(\d+);",
                                    @"-->",
                                    @"<!--.*\n" ,
                                    @"<script[^>]*?>.*?</script>",
                                    @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>"
                                };

        string[] Replaces ={
                                    "",
                                    "\"",
                                    "&",
                                    "<",
                                    ">",
                                    " ",
                                    "\xa1", //chr(161),
                                    "\xa2", //chr(162),
                                    "\xa3", //chr(163),
                                    "\xa9", //chr(169),
                                    "",
                                    "\r\n",
                                    "",
                                    "",
                                    ""
                                };

        string s = HTML;
        for (int i = 0; i < Regexs.Length; i++)
        {
            s = new Regex(Regexs[i], RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(s, Replaces[i]);
        }
        s.Replace("<", "");
        s.Replace(">", "");
        s.Replace("\r\n", "");
        return s;
    }

    #endregion

    #region [ 其它 ]
    /// <summary>
    /// 合并多个HashCode的值
    /// </summary>
    /// <param name="h1"></param>
    /// <param name="h2"></param>
    /// <returns></returns>
    public static int CombineHashCodes(int h1, int h2)
    {
        return (h1 << 5) + h1 ^ h2;
    }
    /// <summary>
    /// 获得文件当前绝对路径
    /// </summary>
    /// <param name="strPath">指定的路径</param>
    /// <returns>绝对路径</returns>
    public static string GetMapPath(string strPath)
    {
        if (HttpContext.Current != null)
        {
            return HttpContext.Current.Server.MapPath(strPath);
        }
        //非web程序引用
        strPath = strPath.Replace("/", "\\");
        if (strPath.StartsWith("\\"))
        {
            //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
            strPath = strPath.TrimStart('\\');

        }
        return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
    }

    /// <summary>
    /// 上一个页面
    /// </summary>
    public static string GetReferrerUrl(string defaultUrl)
    {
        if (HttpContext.Current.Request.UrlReferrer == null)
            return defaultUrl;
        else
        {
            return HttpContext.Current.Request.UrlReferrer.ToString();
        }
    }

    /// <summary>
    /// 组成URL
    /// </summary>
    /// <param name="_page">要请求的页码</param>
    /// <returns></returns>
    public static string GetUrl(int _page)
    {
        string[] urlInfo = HttpUtility.UrlDecode(HttpContext.Current.Request.Url.ToString()).Split('?');
        Dictionary<string, string> dic = new Dictionary<string, string>();
        NameValueCollection urlParams = HttpContext.Current.Request.QueryString;
        foreach (string i in urlParams.AllKeys)
        {
            dic.Add(i, urlParams[i]);
        }

        if (null != dic && dic.Count > 0)
        {
            if (dic.ContainsKey("page"))
            { dic["page"] = _page.ToString(); }
            else
            { dic.Add("page", _page.ToString()); }
        }
        else
        {
            dic.Add("page", _page.ToString());
        }

        string strUrl = urlInfo[0] + "?";

        int j = 1;//计数器
        foreach (KeyValuePair<string, string> i in dic)
        {
            if (j == 1)
            {
                strUrl += i.Key + "=" + i.Value;
                j++;
            }
            else
            {
                strUrl += "&" + i.Key + "=" + i.Value;
                j++;
            }
        }
        return strUrl;
    }

    #endregion

    #region [ 业务操作方法 ]

    /// <summary>
    /// 获取一级菜单重写名称
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    public static string GetLanmuUrlNmae(int pid)
    {
        if (pid == AboutCid)
        {
            return "about";
        }
        else if (pid == IndustryCid)
        {

            return "industry";
        }
        else if (pid == RfsocietyCid)
        {

            return "rfsociety";
        }
        else if (pid == JoinCid)
        {

            return "join";
        }
        return "暂无配置该菜单";
    }

    /// <summary>
    /// 判定当前用户是否有访问某个页面的权限
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static bool HasPageRight(string _url)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            FormsAuthentication.RedirectToLoginPage();
            HttpContext.Current.Response.End();
        }
        if (HttpContext.Current.User.Identity.Name == ConfigurationSettings.AppSettings["superuser"]) return true;

        //给定url的模块信息
        string strSql = "select * from [SysModule] where [href]='" + _url + "'";
        SqlManage sqlM = SqlManage.GetInstance();
        DataSet ds = sqlM.GetDataSet(CommandType.Text, strSql);

        //当前用户信息
        strSql = "select [moduleids] from [SysUser] where [username]='" + HttpContext.Current.User.Identity.Name + "'";
        object obj = sqlM.GetFistColumn(CommandType.Text, strSql);

        if (null != ds && null != ds.Tables[0] && ds.Tables[0].Rows.Count > 0)
        {
            if (null != obj && DBNull.Value != obj)
            {
                string[] mids = obj.ToString().Split(',');
                foreach (string i in mids)
                {
                    if (i == ds.Tables[0].Rows[0]["moduleid"].ToString()) { return true; }
                }
            }
        }

        return false;
    }

    /// <summary>
    /// 最新4条新闻
    /// </summary>
    public static void InitNewsXml()
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        doc.AppendChild(dec);
        //创建document根节点
        XmlNode info = doc.CreateElement("info");
        doc.AppendChild(info);

        //初始内容
        DataSet ds = CustomQuery.Article_GetArticleNewsByCId(5, Utility.NewsCid, " and A_Top like '%B%'", "");
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                XmlNode news = doc.CreateElement("news");
                info.AppendChild(news);

                XmlAttribute title = doc.CreateAttribute("title");
                title.InnerText = dr["A_Title"].ToString();
                news.Attributes.Append(title);

                XmlAttribute date = doc.CreateAttribute("date");
                date.InnerText = dr["A_InDate"].ToDateTime().ToString("yyyy-MM-dd");
                news.Attributes.Append(date);

                XmlAttribute Tourl = doc.CreateAttribute("Tourl");
                Tourl.InnerText = "/news-" + dr["A_Id"].ToString() + ".html";
                news.Attributes.Append(Tourl);
            }
        }
        doc.Save(Utility.GetMapPath("/config/news.xml"));
    }
    /// <summary>
    /// 
    /// </summary>
    public static void InitNews2Xml()
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        doc.AppendChild(dec);
        //创建document根节点
        XmlNode _new = doc.CreateElement("new");
        doc.AppendChild(_new);

        //初始内容

        #region [ 日发精机 ]
        string photoPic = "/images/rfjingji.jpg", photoTitle = "日发精机股票代码：002520", photoUrl = "http://finance.sina.com.cn/realstock/company/sz002520/nc.shtml";
        // 日发精机图片
        XmlNode photoPicPart = doc.CreateElement("part");
        _new.AppendChild(photoPicPart);
        XmlAttribute photoPicPartTitle = doc.CreateAttribute("title");
        photoPicPartTitle.InnerText = photoPic;
        photoPicPart.Attributes.Append(photoPicPartTitle);

        // 日发精机标题
        XmlNode photoTitlePart = doc.CreateElement("part");
        _new.AppendChild(photoTitlePart);
        XmlAttribute photoTitlePartTitle = doc.CreateAttribute("title");
        photoTitlePartTitle.InnerText = photoTitle;
        photoTitlePart.Attributes.Append(photoTitlePartTitle);

        // 日发精机地址
        XmlNode photoUrlPart = doc.CreateElement("part");
        _new.AppendChild(photoUrlPart);
        XmlAttribute photoUrlPartTitle = doc.CreateAttribute("title");
        photoUrlPartTitle.InnerText = photoUrl;
        photoUrlPart.Attributes.Append(photoUrlPartTitle);

        #endregion

        #region [ 日发视频 ]
        string videoPic = "", videoUrl = "";//Setting(SiteUrl);
        DataSet videoDs = CustomQuery.Article_GetArticleNewsByCId(1, Utility.VodeoCid, " and A_Top like '%B%'", "");
        if (videoDs != null && videoDs.Tables.Count > 0 && videoDs.Tables[0].Rows.Count > 0)
        {
            videoPic = videoDs.Tables[0].Rows[0]["A_VideoUrl"].ToString();
            videoUrl += "/video-" + videoDs.Tables[0].Rows[0]["A_Id"].ToString() + ".html";
        }
        // 视频图片
        XmlNode picPart = doc.CreateElement("part");
        _new.AppendChild(picPart);
        XmlAttribute picPartTitle = doc.CreateAttribute("title");
        picPartTitle.InnerText = videoPic;
        picPart.Attributes.Append(picPartTitle);

        // 视频地址
        XmlNode urlPart = doc.CreateElement("part");
        _new.AppendChild(urlPart);
        XmlAttribute urlPartTitle = doc.CreateAttribute("title");
        urlPartTitle.InnerText = videoUrl;
        urlPart.Attributes.Append(urlPartTitle);
        #endregion

        doc.Save(Utility.GetMapPath("/config/news2.xml"));
    }

    #endregion

    #region 日志操作

    /// <summary>
    /// 写入Info级日志
    /// </summary>
    /// <param name="message"></param>
    public static void WriteInfoLog(string message)
    {
        WriteInfoLog(message, null);
    }

    /// <summary>
    /// 写入Info级日志
    /// </summary>
    /// <param name="ex"></param>
    public static void WriteInfoLog(Exception ex)
    {
        WriteInfoLog("程序错误", ex);

    }
    /// <summary>
    /// 写入Info级日志
    /// </summary>
    /// <param name="message"></param>
    /// <param name="ex"></param>
    public static void WriteInfoLog(string message, Exception ex)
    {
        Function.WriteInfoLog(message, ex);
    }
    /// <summary>
    /// 写入Error级日志
    /// </summary>
    /// <param name="message"></param>
    public static void WriteErrorLog(string message)
    {
        WriteErrorLog(message, null);
    }
    /// <summary>
    /// 写入Error级日志
    /// </summary>
    /// <param name="ex"></param>
    public static void WriteErrorLog(Exception ex)
    {
        WriteErrorLog("程序错误", ex);

    }
    /// <summary>
    /// 写入Error级日志
    /// </summary>
    /// <param name="message"></param>
    /// <param name="ex"></param>
    public static void WriteErrorLog(string message, Exception ex)
    {
        Function.WriteErrorLog(message, ex);
    }

    #endregion

    #region [ 生成缩略图 ]

    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图片路径（相对路径）</param>
    /// <param name="Stream">缩略图路径（相对路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>
    public static bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumMode mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(originalImagePath));
        bool rel = MakeThumbnail(originalImage, thumbnailPath, width, height, mode);
        originalImage.Dispose();
        return rel;
    }

    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图片路径（相对路径）</param>
    /// <param name="Stream">缩略图路径（相对路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>
    public static bool MakeThumbnail(System.Drawing.Image srcImage, string thumbnailPath, int width, int height, ThumMode mode)
    {
        System.Drawing.Image originalImage = srcImage;
        bool bret = false;  //返回值
        int towidth = width;
        int toheight = height;
        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        switch (mode)
        {
            case ThumMode.AutoFill://指定高宽缩放（可能变形）                
                break;
            case ThumMode.OnlyWidth://指定宽，高按比例                    
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case ThumMode.OnlyHeight://指定高，宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case ThumMode.AutoZoom://指定高宽裁减（不变形）                
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            case ThumMode.AutoZoomIn: //自动缩小方式
                if (ow > towidth) // 120 > 90 
                {
                    if (((double)ow) / ((double)oh) > ((double)towidth) / ((double)toheight))
                    {
                        toheight = oh * towidth / ow;
                    }
                    else
                    {
                        towidth = ow * toheight / oh;
                    }
                }
                else  // 45  < 200
                {
                    if (oh <= toheight)  // 45  < 150
                    {
                        towidth = ow;
                        toheight = oh;
                    }
                    else   // 750  > 150
                    {
                        towidth = ow * toheight / oh;
                    }
                }
                break;
            case ThumMode.AutoZoomOut: //自动放大方式
                if (ow < towidth)
                {
                    if (((double)ow) / ((double)oh) > ((double)towidth) / ((double)toheight))
                    {
                        toheight = oh * towidth / ow;
                    }
                    else
                    {
                        towidth = ow * toheight / oh;
                    }
                }
                if (oh >= toheight)
                {
                    towidth = ow;
                    toheight = oh;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //以原图片格式保存
            bitmap.Save(HttpContext.Current.Server.MapPath(thumbnailPath), originalImage.RawFormat);//System.Drawing.Imaging.ImageFormat.Jpeg
            bret = true;
        }
        catch (Exception ex)
        {
            Utility.WriteErrorLog(ex);
        }
        finally
        {//释放资源
            bitmap.Dispose();
            g.Dispose();
            originalImage.Dispose();
        }

        return bret;
    }

    /// <summary>
    /// 缩略图生成方式
    /// </summary>
    public enum ThumMode
    {
        /// <summary>
        /// 自动缩小方式。该方式将在原图片与缩略图比例不符时，若原图宽和高都小于缩略图宽和高时,将不做处理；否则将根据需要的缩略图自动将原图片按比例缩小。所生成的缩略图的尺寸将会小于等于所设置的宽和高。 
        /// </summary>
        AutoZoomOut,
        /// <summary>
        /// 自动放大方式。该方式将在原图片与缩略图比例不符时，若原图宽和高都大于缩略图宽和高时,将不做处理；否则将根据需要的缩略图自动将原图片按比例放大。所生成的缩略图的尺寸将会大于等于原图的宽和高。 
        /// </summary>
        AutoZoomIn,
        /// <summary>
        /// 自动缩放方式。该方式将在原图片与缩略图比例不符时，根据需要的缩略图自动将原图片按比例缩小或放大。所生成的缩略图的宽度/高度会严格等于所设置的宽度/高度,对应高度/宽度有可能随原图比例而自动调整。 
        /// </summary>
        AutoZoom,
        /// <summary>
        /// 自动裁剪方式。该方式将在原图片与缩略图比例不符时，将根据需要的缩略图自动从原图片的中间按比例裁剪。所生成的缩略图的尺寸将会严格等于所设置的宽和高。 
        /// </summary>
        AutoCut,
        /// <summary>
        /// 自动填充方式。该方式将在原图片与缩略图比例不符时，将根据需要的缩略图自动将原图片按比例缩小，空白处以白色填充。所生成的缩略图的尺寸将会严格等于所设置的宽和高。 
        /// </summary>
        AutoFill,
        /// <summary>
        /// 强行缩放方式。该方式会将图片根据指定的缩略图宽和高生成缩略图。如果原图片比例与缩略图比例不符，将会强行将图片变形缩放生成缩略图。所生成的缩略图的尺寸将会严格等于所设置的宽和高。
        /// </summary>
        ForceZoom,
        /// <summary>
        /// 仅考虑宽方式。该方式将在原图片与缩略图比例不符时，将只符合缩略图所要求的宽度，不进行裁减也不进行变形。所生成的缩略图的宽度会严格等于所设置的宽，高度有可能随原图比例而自动调整。 
        /// </summary>
        OnlyWidth,
        /// <summary>
        /// 仅考虑高方式。该方式将在原图片与缩略图比例不符时，将只符合缩略图所要求的高度，不进行裁减也不进行变形。所生成的缩略图的高度会严格等于所设置的高，宽度有可能随原图比例而自动调整。 
        /// </summary>
        OnlyHeight
    }
    #endregion
}

#region [ 工具类 ]

/// <summary>
/// 自定义SQL语句类
/// </summary>
public class CustomQuery
{
    #region 图片中心

    /// <summary>
    /// 新建图片中心
    /// </summary>
    /// <param name="CId">关联ID</param>
    /// <param name="Summary">简介</param>
    /// <param name="BigSrc">原始图片</param>
    /// <param name="SmallSrc">缩略图片</param>
    /// <param name="Sort">排序</param>
    /// <param name="InUser">插入用户</param>
    /// <returns></returns>
    public static int PhotoImg_Add(int CId, string Summary, string BigSrc, string SmallSrc, int Sort, string InUser)
    {
        string strSql = "insert into [PhotoImgs]([CId],[Summary],[BigSrc],[SmallSrc],[Sort],[InUser],[InDate])" +
                        "values(@CId,@Summary,@BigSrc,@SmallSrc,@Sort,@InUser,@InDate)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@CId",CId), 
                                        new OleDbParameter("@Summary",Summary), 
                                        new OleDbParameter("@BigSrc",BigSrc),
                                        new OleDbParameter("@SmallSrc",SmallSrc),
                                        new OleDbParameter("@Sort",Sort+1),
                                        new OleDbParameter("@InUser",InUser),
                                        new OleDbParameter("@InDate",DateTime.Now.ToString())
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新图片中心
    /// </summary>
    /// <param name="Id">ID</param>
    /// <param name="Summary">简介</param>
    /// <param name="Sort">排序</param>
    /// <returns></returns>
    public static int PhotoImg_Update(int Id, string Summary, int Sort)
    {
        string strSql = "update [PhotoImgs] set [Summary]=@Summary,[Sort]=@Sort where [Id]=@Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@Summary",Summary), 
                                        new OleDbParameter("@Sort",Sort),
                                        new OleDbParameter("@Id",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新图片中心
    /// </summary>
    /// <param name="Id">ID</param>
    /// <param name="CId">关联ID</param>
    /// <param name="Summary">简介</param>
    /// <param name="BigSrc">原始图片</param>
    /// <param name="SmallSrc">缩略图片</param>
    /// <returns></returns>
    public static int PhotoImg_Update(int Id, int CId, string Summary, string BigSrc, string SmallSrc)
    {
        string strSql = "update [PhotoImgs] set [CId]=@CId,[Summary]=@Summary,[BigSrc]=@BigSrc,[SmallSrc]=@SmallSrc where [Id]=@Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@CId",CId), 
                                        new OleDbParameter("@Summary",Summary), 
                                        new OleDbParameter("@BigSrc",BigSrc),
                                        new OleDbParameter("@SmallSrc",SmallSrc),
                                        new OleDbParameter("@Id",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 删除图片中心
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="id">新闻信息ID</param>
    /// <returns></returns>
    public static int PhotoImg_Delete(int id)
    {
        string strSql = "delete from [PhotoImgs] where [Id]=@Id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@Id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据ID获取图片中心
    /// </summary>
    /// <param name="id">ID</param>
    /// <returns></returns>
    public static DataSet PhotoImg_GetPhotoImgById(int id)
    {
        string strSql = "select * from [PhotoImgs] where [Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@Id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据关联ID获取图片中心
    /// </summary>
    /// <param name="Cid">关联ID</param>
    /// <returns></returns>
    public static DataSet PhotoImg_GetPhotoImgByCid(int Cid)
    {
        string strSql = "select * from [PhotoImgs] where [Cid]=@Cid order by [Sort] desc";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@Cid",Cid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取图片中心
    /// </summary>
    /// <returns></returns>
    public static DataSet PhotoImg_GetPhotoImgs()
    {
        string strSql = "select * from [PhotoImgs] order by [Sort] desc";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    /// <summary>
    /// 根据ID获取图片中心最大Sort
    /// </summary>
    /// <param name="Cid">关联ID</param>
    /// <returns></returns>
    public static object PhotoImg_GetMaxSortByCid(int Cid)
    {
        string strSql = "select max([Sort]) from [PhotoImgs] where [Cid]=@Cid";
        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@Cid",Cid)
                                       };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }
    #endregion

    #region 招聘信息

    /// <summary>
    /// 插入招聘信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Name">职位名称</param>
    /// <param name="NeedNum">招聘人数</param>
    /// <param name="Shalary">工资待遇</param>
    /// <param name="WorkingPlace">工作地点</param>
    /// <param name="RequiredDegree">学历要求</param>
    /// <param name="Sex">性别要求</param>
    /// <param name="Department">所属部门</param>
    /// <param name="WorkExperience">工作经验</param>
    /// <param name="Description">职位描述</param>
    /// <param name="EffectiveDate">结束时间</param>
    /// <returns></returns>
    public static int Job_Add(string Name, int NeedNum, int Shalary, string WorkingPlace, int RequiredDegree, int Sex, string Department, int WorkExperience, string Description, DateTime? EffectiveDate)
    {
        string strSql = "insert into [Job]([J_Name],[J_NeedNum],[J_Shalary],[J_WorkingPlace],[J_RequiredDegree],[J_Sex],[J_Department],[J_WorkExperience],[J_Description],[J_InDate],[J_EffectiveDate])" +
                        "values(@J_Name,@J_NeedNum,@J_Shalary,@J_WorkingPlace,@J_RequiredDegree,@J_Sex,@J_Department,@J_WorkExperience,@J_Description,@J_InDate,@J_EffectiveDate)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@J_Name",Name), 
                                        new OleDbParameter("@J_NeedNum",NeedNum), 
                                        new OleDbParameter("@J_Shalary",Shalary),
                                        new OleDbParameter("@J_WorkingPlace",WorkingPlace),
                                        new OleDbParameter("@J_RequiredDegree",RequiredDegree),
                                        new OleDbParameter("@J_Sex",Sex),
                                        new OleDbParameter("@J_Department",Department),
                                        new OleDbParameter("@J_WorkExperience",WorkExperience),
                                        new OleDbParameter("@J_Description",Description),
                                        new OleDbParameter("@J_InDate",DateTime.Now.ToString()),
                                        new OleDbParameter("@J_EffectiveDate",EffectiveDate==null?"":EffectiveDate.ToString())
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新招聘信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Id">职位ID</param>
    /// <param name="Name">职位名称</param>
    /// <param name="NeedNum">招聘人数</param>
    /// <param name="Shalary">工资待遇</param>
    /// <param name="WorkingPlace">工作地点</param>
    /// <param name="RequiredDegree">学历要求</param>
    /// <param name="Sex">学历要求</param>
    /// <param name="Department">所属部门</param>
    /// <param name="WorkExperience">工作经验</param>
    /// <param name="Description">职位描述</param>
    /// <param name="EffectiveDate">结束时间</param>
    /// <returns></returns>
    public static int Job_Update(int Id, string Name, int NeedNum, int Shalary, string WorkingPlace, int RequiredDegree, int Sex, string Department, int WorkExperience, string Description, DateTime? EffectiveDate)
    {
        string strSql = "update [Job] set [J_Name]=@J_Name,[J_NeedNum]=@J_NeedNum,[J_Shalary]=@J_Shalary,[J_WorkingPlace]=@J_WorkingPlace,[J_RequiredDegree]=@J_RequiredDegree,[J_Sex]=@J_Sex" +
                        ",[J_Department]=@J_Department,[J_WorkExperience]=@J_WorkExperience,[J_Description]=@J_Description,[J_EffectiveDate]=@J_EffectiveDate where [J_Id]=@J_Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@J_Name",Name), 
                                        new OleDbParameter("@J_NeedNum",NeedNum), 
                                        new OleDbParameter("@J_Shalary",Shalary),
                                        new OleDbParameter("@J_WorkingPlace",WorkingPlace),
                                        new OleDbParameter("@J_RequiredDegree",RequiredDegree),
                                        new OleDbParameter("@J_Sex",Sex),
                                        new OleDbParameter("@J_Department",Department),
                                        new OleDbParameter("@J_WorkExperience",WorkExperience),
                                        new OleDbParameter("@J_Description",Description),
                                        new OleDbParameter("@J_EffectiveDate",EffectiveDate==null?"":EffectiveDate.ToString()),
                                        new OleDbParameter("@J_Id",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 删除招聘信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="id">招聘信息ID</param>
    /// <returns></returns>
    public static int Job_Delete(int id)
    {
        string strSql = "delete from [Job] where [J_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据ID获取招聘信息
    /// </summary>
    /// <param name="id">招聘信息ID</param>
    /// <returns></returns>
    public static DataSet Job_GetJobById(int id)
    {
        string strSql = "select * from [Job] where [J_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取招聘信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Job_GetJobs()
    {
        string strSql = "select * from [Job] order by [J_InDate] desc";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    /// <summary>
    /// 获取分页招聘信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Job_GetJobsByPage(ref PageStructure ps)
    {
        return Job_GetJobsByPage("J_InDate", "desc", "", ref ps);
    }
    /// <summary>
    /// 获取分页招聘信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Job_GetJobsByPage(string strwhere, ref PageStructure ps)
    {
        return Job_GetJobsByPage("J_InDate", "desc", strwhere, ref ps);
    }
    /// <summary>
    /// 获取分页招聘信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Job_GetJobsByPage(string OrderField, string OrderDirection, string strwhere, ref PageStructure ps)
    {
        string strSql = "", pageSql = "";

        if (ps.CurrPage > 1)
            strSql = "select top " + ps.PageSize + " * from [Job] where [J_Id] not in(select top " + (ps.CurrPage - 1) * ps.PageSize + " [J_Id] from [Job] where 1=1";
        else
            strSql = "select top " + ps.PageSize + " * from [Job] where 1=1";

        if (ps.CurrPage > 1)
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + ")" + strwhere + " order by [" + OrderField + "] " + OrderDirection + "";
        else
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + "";

        pageSql += "select count(*) from Job where 1=1 " + strwhere;
        object allCount = SqlManage.GetInstance().GetFistColumn(CommandType.Text, pageSql);
        if (DBNull.Value != allCount && null != allCount)
        {
            ps.Counts = allCount.ToInt();
            ps.PageCount = (ps.Counts % ps.PageSize == 0) ? ps.Counts / ps.PageSize : ps.Counts / ps.PageSize + 1;
        }
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    #endregion

    #region 新闻信息

    /// <summary>
    /// 新增新闻信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Cateid">文章分类ID</param>
    /// <param name="Title">标题</param>
    /// <param name="keyWord">关键字</param>
    /// <param name="Pic">展示图片src</param>
    /// <param name="Summary">简介</param>
    /// <param name="Content">内容</param>
    /// <returns></returns>
    public static int Article_Add(int Cateid, string Title, string keyWord, string Pic, string Summary, string Content, string userName, string top, string videoUrl)
    {
        string strSql = "insert into [Article]([A_Cateid],[A_Title],[A_keyWord],[A_Pic],[A_Summary],[A_Content],[A_InUser],[A_InDate],[A_UpDate],[A_Click],[A_Top],[A_VideoUrl])" +
                        "values(@A_Cateid,@A_Title,@A_keyWord,@A_Pic,@A_Summary,@A_Content,@A_InUser,@A_InDate,@A_UpDate,@A_Click,@A_Top,@A_VideoUrl)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@A_Cateid",Cateid), 
                                        new OleDbParameter("@A_Title",Title), 
                                        new OleDbParameter("@A_keyWord",keyWord),
                                        new OleDbParameter("@A_Pic",Pic),
                                        new OleDbParameter("@A_Summary",Summary),
                                        new OleDbParameter("@A_Content",Content),
                                        new OleDbParameter("@A_InUser",userName),
                                        new OleDbParameter("@A_InDate",DateTime.Now.ToString()),
                                        new OleDbParameter("@A_UpDate",DateTime.Now.ToString()),
                                        new OleDbParameter("@A_Click",1),
                                        new OleDbParameter("@A_Top",top),
                                        new OleDbParameter("@A_VideoUrl",videoUrl)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新新闻信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Id">新闻ID</param>
    /// <param name="Cateid">文章分类ID</param>
    /// <param name="Title">标题</param>
    /// <param name="keyWord">关键字</param>
    /// <param name="Pic">展示图片src</param>
    /// <param name="Summary">简介</param>
    /// <param name="Content">内容</param>
    /// <returns></returns>
    public static int Article_Update(int Id, int Cateid, string Title, string keyWord, string Pic, string Summary, string Content, string top, string videoUrl)
    {
        string strSql = "update [Article] set [A_Cateid]=@A_Cateid,[A_Title]=@A_Title,[A_keyWord]=@A_keyWord,[A_Pic]=@A_Pic,[A_Summary]=@A_Summary,[A_Content]=@A_Content,[A_UpDate]=@A_UpDate,[A_Top]=@A_Top,[A_VideoUrl]=@A_VideoUrl where [A_Id]=@A_Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@A_Cateid",Cateid), 
                                        new OleDbParameter("@A_Title",Title), 
                                        new OleDbParameter("@A_keyWord",keyWord),
                                        new OleDbParameter("@A_Pic",Pic),
                                        new OleDbParameter("@A_Summary",Summary),
                                        new OleDbParameter("@A_Content",Content),
                                        new OleDbParameter("@A_UpDate",DateTime.Now.ToString()),
                                        new OleDbParameter("@A_Top",top),
                                        new OleDbParameter("@A_VideoUrl",videoUrl),
                                        new OleDbParameter("@A_Id",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 浏览量+1
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Id">新闻ID</param>
    /// <returns></returns>
    public static int Article_ViewClick(int Id)
    {
        string strSql = "update [Article] set [A_Click]=A_Click+1 where [A_Id]=@A_Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@A_Id",Id)
                                    };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 删除新闻信息
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="id">新闻信息ID</param>
    /// <returns></returns>
    public static int Article_Delete(int id)
    {
        string strSql = "delete from [Article] where [A_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据ID获取新闻信息
    /// </summary>
    /// <param name="id">新闻信息ID</param>
    /// <returns></returns>
    public static DataSet Article_GetArticleById(int id)
    {
        string strSql = "select * from [Article] where [A_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取新闻信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Article_GetArticles()
    {
        string strSql = "select * from [Article] order by [A_InDate] desc";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    /// <summary>
    /// 获取上1条新闻
    /// </summary>
    /// <param name="cid">新闻分类ID</param>
    /// <param name="id">新闻信息ID</param>
    /// <returns></returns>
    public static DataSet Article_GetPreArticleById(int cid, int id)
    {
        string strSql = "select top 1 * from [Article] where [A_Cateid]=@cid and [A_Id]>@id order by A_InDate";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@cid",cid),
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取下1条新闻
    /// </summary>
    /// <param name="cid">新闻分类ID</param>
    /// <param name="id">新闻信息ID</param>
    /// <returns></returns>
    public static DataSet Article_GetNextArticleById(int cid, int id)
    {
        string strSql = "select top 1 * from [Article] where [A_Cateid]=@cid and [A_Id]<@id order by A_InDate desc";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@cid",cid),
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 获取新闻信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Article_GetArticlesByPage(ref PageStructure ps)
    {
        return Article_GetArticlesByPage("A_InDate", "desc", "", ref ps);
    }
    /// <summary>
    /// 获取新闻信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Article_GetArticlesByPage(string strwhere, ref PageStructure ps)
    {
        return Article_GetArticlesByPage("A_InDate", "desc", strwhere, ref ps);
    }
    /// <summary>
    /// 获取新闻信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Article_GetArticlesByPage(string OrderField, string OrderDirection, string strwhere, ref PageStructure ps)
    {
        string strSql = "", pageSql = "";

        if (ps.CurrPage > 1)
            strSql = "select top " + ps.PageSize + " * from [Article] where [A_Id] not in(select top " + (ps.CurrPage - 1) * ps.PageSize + " [A_Id] from [Article] where 1=1";
        else
            strSql = "select top " + ps.PageSize + " * from [Article] where 1=1";

        if (ps.CurrPage > 1)
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + ")" + strwhere + " order by [" + OrderField + "] " + OrderDirection + "";
        else
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + "";

        pageSql += "select count(*) from Article where 1=1 " + strwhere;
        object allCount = SqlManage.GetInstance().GetFistColumn(CommandType.Text, pageSql);
        if (DBNull.Value != allCount && null != allCount)
        {
            ps.Counts = allCount.ToInt();
            ps.PageCount = (ps.Counts % ps.PageSize == 0) ? ps.Counts / ps.PageSize : ps.Counts / ps.PageSize + 1;
        }
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }

    /// <summary>
    /// 根据分类获取指定条数数据
    /// </summary>
    /// <param name="top">条数</param>
    /// <param name="cid">分类ID</param>
    /// <returns></returns>
    public static DataSet Article_GetArticlePicByCId(int top, int cid)
    {
        string strSql = "select top " + top + " * from [Article] where A_Pic <> '' and [A_Cateid]=@cid order by A_InDate desc";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@cid",cid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据分类获取指定条数数据
    /// </summary>
    /// <param name="top">条数</param>
    /// <param name="cid">分类ID</param>
    /// <param name="notinid">不查询指定id</param>
    /// <returns></returns>
    public static DataSet Article_GetArticleNewsByCId(int top, int cid, string notinid)
    {
        string strSql = "select top " + top + " * from [Article] where [A_Cateid]=@cid";
        strSql += notinid.IsNotNullAndEmpty() ? " and A_Id not in (" + notinid + ")" : "";
        strSql += " order by A_InDate desc";
        OleDbParameter[] oleParams ={
                                 new OleDbParameter("@cid",cid)
                                 };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据分类获取指定条数数据
    /// </summary>
    /// <param name="top">条数</param>
    /// <param name="cid">分类ID</param>
    /// <param name="notinid">不查询指定id</param>
    /// <returns></returns>
    public static DataSet Article_GetArticleNewsByCId(int top, int cid, string where, string notinid)
    {
        string strSql = "select top " + top + " * from [Article] where [A_Cateid]=@cid";
        strSql += where.IsNotNullAndEmpty() ? where : "";
        strSql += notinid.IsNotNullAndEmpty() ? " and A_Id not in (" + notinid + ")" : "";
        strSql += " order by A_InDate desc";
        OleDbParameter[] oleParams ={
                                 new OleDbParameter("@cid",cid)
                                 };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);

    }


    #endregion

    #region 分类管理

    /// <summary>
    /// 新增分类管理
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Pid">父ID</param>
    /// <param name="Name">分类名称</param>
    /// <param name="Sort">排序</param>
    /// <param name="enable">是否启用</param>
    /// <returns></returns>
    public static int Category_Add(int Pid, string Name, int Sort, int enable)
    {
        string strSql = "insert into [Category]([C_Pid],[C_Name],[C_Sort],[C_Enable])values(@C_Pid,@C_Name,@C_Sort,@C_Enable)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@C_Pid",Pid), 
                                        new OleDbParameter("@C_Name",Name), 
                                        new OleDbParameter("@C_Sort",Sort+1),
                                        new OleDbParameter("@C_Enable",enable)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新分类管理
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="Id">ID</param>
    /// <param name="Pid">父ID</param>
    /// <param name="Name">分类名称</param>
    /// <param name="Sort">排序</param>
    /// <param name="enable">是否启用</param>
    /// <returns></returns>
    public static int Category_Update(int Id, int Pid, string Name, int enable)
    {
        string strSql = "update [Category] set [C_Pid]=@C_Pid,[C_Name]=@C_Name,[C_Enable]=@C_Enable where [C_Id]=@C_Id";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@C_Pid",Pid), 
                                        new OleDbParameter("@C_Name",Name), 
                                        new OleDbParameter("@C_Enable",enable),
                                        new OleDbParameter("@C_Id",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 清空该分类下的子分类，本身不删除
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static int Category_Empty(string id)
    {
        string strSql = "delete from [Category] where [C_Pid]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 删除分类及子模块
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static int Category_Delete(string id)
    {
        string strSql = "delete from [Category] where [C_Pid]=@id or [C_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取所有分类
    /// </summary>
    /// <returns></returns>
    public static DataSet Category_GetAll()
    {
        string strSql = "select * from [Category] order by [C_Sort]";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    /// <summary>
    /// 根据ID获取分类
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static string Category_GetCNameById(int id)
    {
        if (id <= 0)
        {
            return "";
        }
        string strSql = "select C_Name from [Category] where [C_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        object obj = SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
        return DBNull.Value != obj && null != obj ? obj.ToString() : "";
    }
    /// <summary>
    /// 根据ID获取分类
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static DataSet Category_GetCategoryById(int id)
    {
        string strSql = "select * from [Category] where [C_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据父级ID获取分类
    /// </summary>
    /// <param name="id">父级ID</param>
    /// <returns></returns>
    public static DataSet Category_GetCategoryByPId(int pid)
    {
        string strSql = "select * from [Category] where [C_Pid]=@C_Pid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@C_Pid",pid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据父级ID获取分类
    /// </summary>
    /// <param name="id">父级ID</param>
    /// <returns></returns>
    public static DataSet Category_GetCategoryByPId(int pid, int enable)
    {
        string strSql = "select * from [Category] where [C_Pid]=@C_Pid and [C_Enable]=@C_Enable";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@C_Pid",pid),
                                       new OleDbParameter("@C_Enable",enable)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取分类Sort
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    public static object Category_GetCategorySort(string pid)
    {

        string strSql = "select max([C_Sort]) from [Category] where C_Pid=@pid";
        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@pid",pid)
                                       };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }
    #endregion

    #region 栏目管理

    /// <summary>
    /// 新增栏目管理
    /// </summary>
    /// <returns></returns>
    public static int LanMuInfo_Add(int PCid, int Cid, string Name, string content, int EnableCache, int ArticleCid, string SourceUrl, string UrlName, int Sort, string User, string PicUrl, string PicTitle)
    {
        string strSql = @"insert into [LanMuInfo]( LM_PCid, LM_Cid, LM_Name, LM_Content, LM_EnableCache, LM_ArticleCid, LM_SourceUrl, LM_UrlName, LM_Sort, LM_User, LM_InDate, LM_UpDate, LM_PicUrl, LM_PicTitle)
                                           values(@LM_PCid,@LM_Cid,@LM_Name,@LM_Content,@LM_EnableCache,@LM_ArticleCid,@LM_SourceUrl,@LM_UrlName,@LM_Sort,@LM_User,@LM_InDate,@LM_UpDate,@LM_PicUrl,@LM_PicTitle)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@LM_PCid",PCid), 
                                        new OleDbParameter("@LM_Cid",Cid), 
                                        new OleDbParameter("@LM_Name",Name), 
                                        new OleDbParameter("@LM_Content",content), 
                                        new OleDbParameter("@LM_EnableCache",EnableCache), 
                                        new OleDbParameter("@LM_ArticleCid",ArticleCid), 
                                        new OleDbParameter("@LM_SourceUrl",SourceUrl), 
                                        new OleDbParameter("@LM_UrlName",UrlName), 
                                        new OleDbParameter("@LM_Sort",Sort),
                                        new OleDbParameter("@LM_User",User), 
                                        new OleDbParameter("@LM_InDate",DateTime.Now.ToString()), 
                                        new OleDbParameter("@LM_UpDate",DateTime.Now.ToString()), 
                                        new OleDbParameter("@LM_PicUrl",PicUrl), 
                                        new OleDbParameter("@LM_PicTitle",PicTitle)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新栏目管理
    /// </summary>
    /// <returns></returns>
    public static int LanMuInfo_Update(int cid, string Name, string content, int EnableCache, int ArticleCid, string SourceUrl, string UrlName, int Sort, string PicUrl, string PicTitle)
    {
        string strSql = @"update [LanMuInfo] set [LM_Name]=@LM_Name,[LM_Content]=@LM_Content,[LM_EnableCache]=@LM_EnableCache,[LM_ArticleCid]=@LM_ArticleCid,[LM_SourceUrl]=@LM_SourceUrl,[LM_UrlName]=@LM_UrlName,[LM_Sort]=@LM_Sort,[LM_UpDate]=@LM_UpDate,[LM_PicUrl]=@LM_PicUrl,[LM_PicTitle]=@LM_PicTitle
                        where [LM_Cid]=@LM_Cid";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@LM_Name",Name), 
                                        new OleDbParameter("@LM_Content",content), 
                                        new OleDbParameter("@LM_EnableCache",EnableCache), 
                                        new OleDbParameter("@LM_ArticleCid",ArticleCid), 
                                        new OleDbParameter("@LM_SourceUrl",SourceUrl), 
                                        new OleDbParameter("@LM_UrlName",UrlName), 
                                        new OleDbParameter("@LM_Sort",Sort),
                                        new OleDbParameter("@LM_UpDate",DateTime.Now.ToString()), 
                                        new OleDbParameter("@LM_PicUrl",PicUrl), 
                                        new OleDbParameter("@LM_PicTitle",PicTitle),
                                        new OleDbParameter("@LM_Cid",cid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }


    /// <summary>
    /// 删除栏目管理
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static int LanMuInfo_Delete(int cid)
    {
        string strSql = "delete from [LanMuInfo] where [LM_Cid]=@LM_Cid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@LM_Cid",cid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 删除栏目管理
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static int LanMuInfo_Empty(int pid)
    {
        string strSql = "delete from [LanMuInfo] where [LM_PCid]=@LM_PCid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@LM_PCid",pid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 根据ID栏目管理
    /// </summary>
    /// <param name="id">分类ID</param>
    /// <returns></returns>
    public static DataSet LanMuInfo_GetLanMuInfoById(int id)
    {
        string strSql = "select * from [LanMuInfo] where [LM_Id]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据父级ID获取栏目管理
    /// </summary>
    /// <returns></returns>
    public static DataSet LanMuInfo_GetLanMuInfoByCId(int cid)
    {
        string strSql = "select * from [LanMuInfo] where [LM_Cid]=@cid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@cid",cid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据父级ID获取栏目管理
    /// </summary>
    /// <returns></returns>
    public static DataSet LanMuInfo_GetLanMuInfoByUrlName(string name)
    {
        string strSql = "select * from [LanMuInfo] where [LM_UrlName]=@name";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@name",name)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据父级ID获取栏目管理
    /// </summary>
    /// <param name="id">父级ID</param>
    /// <returns></returns>
    public static DataSet LanMuInfo_GetLanMuInfoByPId(int pid)
    {
        string strSql = "select * from [LanMuInfo] where [LM_PCid]=@pid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@pid",pid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }

    #endregion

    #region 留言
    /// <summary>
    /// 新增留言
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="txtMtitle"></param>
    /// <param name="txtMusername"></param>
    /// <param name="txtMcompname"></param>
    /// <param name="txtMaddress"></param>
    /// <param name="txtMtel"></param>
    /// <param name="txtMfax"></param>
    /// <param name="txtMemail"></param>
    /// <param name="txtMcontent"></param>
    /// <returns></returns>
    public static int Message_Add(string txtMtitle, string txtMusername, string txtMcompname, string txtMblog, string txtMaddress, string txtMtel
       , string txtMfax, string txtMqq, string txtMemail, string txtMcontent)
    {
        return Message_Add(txtMtitle, txtMusername, txtMcompname, txtMblog, txtMaddress, txtMtel, txtMfax, txtMqq, txtMemail, txtMcontent, 0L);
    }
    /// <summary>
    /// 回复留言
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="txtMcontent"></param>
    /// <param name="mreply"></param>
    /// <returns></returns>
    public static int Message_Reply(string txtMcontent, long mreply)
    {
        return Message_Add("", "", "", "", "", "", "", "", "", txtMcontent, mreply);
    }

    private static int Message_Add(string txtMtitle, string txtMusername, string txtMcompname, string txtMblog, string txtMaddress, string txtMtel
        , string txtMfax, string txtMqq, string txtMemail, string txtMcontent, long mreply)
    {
        string strSql = @"insert into [Message]([Mtitle],[Musername],[Mcompname],[Mblog],[Maddress],[Mtel],[Mfax],[Mqq],[Memail],[Mcontent],[Mcteatetime],[Mip],[Mreply]) 
                        values(@Mtitle,@Musername,@Mcompname,@Mblog,@Maddress,@Mtel,@Mfax,@Mqq,@Memail,@Mcontent,@Mcteatetime,@Mip,@Mreply)";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@Mtitle",txtMtitle),
                                       new OleDbParameter("@Musername",txtMusername),
                                       new OleDbParameter("@Mcompname",txtMcompname),
                                       new OleDbParameter("@Mblog",txtMblog),
                                       new OleDbParameter("@Maddress",txtMaddress),
                                       new OleDbParameter("@Mtel",txtMtel),
                                       new OleDbParameter("@Mfax",txtMfax),
                                       new OleDbParameter("@Mqq",txtMqq),
                                       new OleDbParameter("@Memail",txtMemail),
                                       new OleDbParameter("@Mcontent",txtMcontent),
                                       new OleDbParameter("@Mcteatetime",DateTime.Now.ToString()),
                                       new OleDbParameter("@Mip",Utility.GetIP()),
                                       new OleDbParameter("@Mreply",mreply)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    public static string Message_GetReplyContent(long mreply)
    {
        string strSql = @"select [Mcontent] from [Message] where [Mreply]=@ID";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@ID",mreply)
                                       };
        DataSet ds = SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            return Utility.ToString(ds.Tables[0].Rows[0]["Mcontent"]);
        return "";
    }

    public static bool Message_HaveReply(object _proId)
    {
        if (null != _proId && DBNull.Value != _proId)
        {
            string strSql = "select [ID] from [Message] where [Mreply]=" + _proId;
            object obj = SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql);
            if (null != obj && DBNull.Value != obj && Convert.ToInt32(obj) > 0)
                return true;
            else
                return false;
        }
        return false;
    }

    /// <summary>
    /// 删除留言信息
    /// </summary>
    /// <param name="id">留言信息ID</param>
    /// <returns></returns>
    public static int Message_Delete(int id)
    {
        string strSql = "delete from [Message] where [ID]=@ID";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@ID",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取留言信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Message_GetMessageByPage(ref PageStructure ps)
    {
        return Message_GetMessageByPage("Mcteatetime", "desc", "", ref ps);
    }
    /// <summary>
    /// 获取留言信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Message_GetMessageByPage(string strwhere, ref PageStructure ps)
    {
        return Message_GetMessageByPage("Mcteatetime", "desc", strwhere, ref ps);
    }
    /// <summary>
    /// 获取留言信息
    /// </summary>
    /// <returns></returns>
    public static DataSet Message_GetMessageByPage(string OrderField, string OrderDirection, string strwhere, ref PageStructure ps)
    {
        string strSql = "", pageSql = "";

        if (ps.CurrPage > 1)
            strSql = "select top " + ps.PageSize + " * from [Message] where [ID] not in(select top " + (ps.CurrPage - 1) * ps.PageSize + " [ID] from [Message] where 1=1";
        else
            strSql = "select top " + ps.PageSize + " * from [Message] where 1=1";

        if (ps.CurrPage > 1)
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + ")" + strwhere + " order by [" + OrderField + "] " + OrderDirection + "";
        else
            strSql += strwhere + " order by [" + OrderField + "] " + OrderDirection + "";

        pageSql += "select count(*) from Message where 1=1 " + strwhere;
        object allCount = SqlManage.GetInstance().GetFistColumn(CommandType.Text, pageSql);
        if (DBNull.Value != allCount && null != allCount)
        {
            ps.Counts = allCount.ToInt();
            ps.PageCount = (ps.Counts % ps.PageSize == 0) ? ps.Counts / ps.PageSize : ps.Counts / ps.PageSize + 1;
        }
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    #endregion

    #region 友情链接管理

    /// <summary>
    /// 新增友情链接管理
    /// </summary>
    /// <param name="Title">标题</param>
    /// <param name="LinkUrl">链接</param>
    /// <param name="Body">描述</param>
    /// <param name="UserID">用户</param>
    /// <param name="Sort">排序</param>
    /// <returns></returns>
    public static int Link_Add(string Title, string LinkUrl, string Body, string UserID, int Sort)
    {
        string strSql = "insert into [Link]([Title],[LinkUrl],[Body],[UserID],[CreateTime],[Sort])values(@Title,@LinkUrl,@Body,@UserID,@CreateTime,@Sort)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@Title",Title), 
                                        new OleDbParameter("@LinkUrl",LinkUrl), 
                                        new OleDbParameter("@Body",Body), 
                                        new OleDbParameter("@UserID",UserID), 
                                        new OleDbParameter("@CreateTime",DateTime.Now.ToString()), 
                                        new OleDbParameter("@Sort",Sort)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新友情链接管理
    /// </summary>
    /// <param name="Id">Id</param>
    /// <param name="Title">标题</param>
    /// <param name="LinkUrl">链接</param>
    /// <param name="Body">描述</param>
    /// <param name="Sort">排序</param>
    /// <returns></returns>
    public static int Link_Update(int Id, string Title, string LinkUrl, string Body, int Sort)
    {
        string strSql = "update [Link] set [Title]=@Title,[LinkUrl]=@LinkUrl,[Body]=@Body,[Sort]=@Sort where [ID]=@ID";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@Title",Title), 
                                        new OleDbParameter("@LinkUrl",LinkUrl), 
                                        new OleDbParameter("@Body",Body),
                                        new OleDbParameter("@Sort",Sort),
                                        new OleDbParameter("@ID",Id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 删除友情链接管理
    /// </summary>
    /// <param name="id">ID</param>
    /// <returns></returns>
    public static int Link_Delete(int id)
    {
        string strSql = "delete from [Link] where [ID]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取所有友情链接管理
    /// </summary>
    /// <returns></returns>
    public static DataSet Link_GetAll()
    {
        string strSql = "select * from [Link] order by [Sort]";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    /// <summary>
    /// 根据ID获取友情链接管理
    /// </summary>
    /// <param name="id">ID</param>
    /// <returns></returns>
    public static DataSet Link_GetLinkById(int id)
    {
        string strSql = "select * from [Link] where [ID]=@id";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@id",id)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据ID获取友情链接最大Sort
    /// </summary>
    /// <returns></returns>
    public static object Link_GetMaxSort()
    {
        string strSql = "select max([Sort]) from [Link]";
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql);
    }
    #endregion

    #region 模块管理

    /// <summary>
    /// 新增模块管理
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="mid">模块编号</param>
    /// <param name="parentid">模块编号</param>
    /// <param name="mname">模块名称</param>
    /// <param name="mtitle">模块显示名称</param>
    /// <param name="href">链接页面</param>
    /// <param name="sort">排列顺序</param>
    /// <returns></returns>
    public static int SysModule_Add(string mid, string parentid, string mname, string mtitle, string href, int sort)
    {
        string strSql = "insert into [SysModule]([moduleid],[parentid],[mname],[mtitle],[href],[sort])values(@moduleid,@parentid,@mname,@mtitle,@href,@sort)";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@moduleid",mid),
                                       new OleDbParameter("@parentid",parentid),
                                       new OleDbParameter("@mname",mname),
                                       new OleDbParameter("@mtitle",mtitle),
                                       new OleDbParameter("@href",href),
                                       new OleDbParameter("@sort",sort+1)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新模块管理
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="mid">模块编号</param>
    /// <param name="parentid">模块编号</param>
    /// <param name="mname">模块名称</param>
    /// <param name="mtitle">模块显示名称</param>
    /// <param name="href">链接页面</param>
    /// <returns></returns>
    public static int SysModule_Update(string moduleid, string parentid, string mname, string mtitle, string href)
    {
        string strSql = "update SysModule set [parentid]=@parentid,[mname]=@mname,[mtitle]=@mtitle,[href]=@href where [moduleid]=@moduleid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@parentid",parentid),
                                       new OleDbParameter("@mname",mname),
                                       new OleDbParameter("@mtitle",mtitle),
                                       new OleDbParameter("@href",href),
                                       new OleDbParameter("@moduleid",moduleid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 清空该模块下的子模块，本身不删除
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="moduleid">模块Id</param>
    /// <returns></returns>
    public static int SysModule_Empty(string moduleid)
    {
        string strSql = "delete from [SysModule] where [parentid]=@moduleid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@moduleid",moduleid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 删除该模块及子模块
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="userid">用户编号</param>
    /// <returns></returns>
    public static int SysModule_Delete(string moduleid)
    {
        string strSql = "delete from [SysModule] where [parentid]=@moduleid or [moduleid]=@moduleid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@moduleid",moduleid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 获取用户权限模块
    /// </summary>
    /// <param name="moduleid"></param>
    /// <returns></returns>
    public static DataSet SysModule_GetUserModule(string moduleid)
    {
        if (string.IsNullOrEmpty(moduleid))
        {
            string strSql = "select * from [SysModule] order by [sort]";
            return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
        }
        else
        {
            string strSql = "select * from [SysModule] where moduleid in(" + moduleid + ") order by [sort]";
            return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
        }
    }
    /// <summary>
    /// 获取用户权限模块
    /// </summary>
    /// <param name="moduleid"></param>
    /// <returns></returns>
    public static DataSet SysModule_GetModuleByName(string name)
    {
        if (string.IsNullOrEmpty(name))
        {
            string strSql = "select * from [SysModule] order by [sort]";
            return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
        }
        else
        {
            string strSql = "select * from [SysModule] where mname like '%'+@mname+'%' order by [sort]";
            OleDbParameter[] oleParams ={
                                       new OleDbParameter("@mname",name)
                                       };
            return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
        }
    }
    /// <summary>
    /// 获取用户权限模块
    /// </summary>
    /// <param name="moduleid"></param>
    /// <returns></returns>
    public static DataSet SysModule_GetModuleById(string moduleid)
    {

        string strSql = "select * from [SysModule] where moduleid=@moduleid";
        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@moduleid",moduleid)
                                       };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取用户权限模块
    /// </summary>
    /// <param name="moduleid"></param>
    /// <returns></returns>
    public static object SysModule_GetModuleSort(string parentid)
    {

        string strSql = "select max([sort]) from [SysModule] where parentid=@parentid";
        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@parentid",parentid)
                                       };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据ID获取用户模块最大Mid
    /// </summary>
    /// <returns></returns>
    public static object SysModule_GetMaxMidByPid(string parentid)
    {
        string strSql = "select max([moduleid]) from [SysModule] where parentid=@parentid";
        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@parentid",parentid)
                                       };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }
    #endregion

    #region 用户管理

    /// <summary>
    /// 新增用户管理
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <returns></returns>
    public static int SysUser_Add(string username, string password, string moduleids, string currUser)
    {
        string strSql = "insert into SysUser([username],[password],[moduleids],[addusername],[addtime])values(@username,@password,@moduleids,@addusername,@addtime)";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@username",username),
                                        new OleDbParameter("@password",Utility.Encrypt(password)),
                                        new OleDbParameter("@moduleids",moduleids),
                                        new OleDbParameter("@addusername",currUser),
                                        new OleDbParameter("@addtime",DateTime.Now.ToString())
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新密码
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="userid">用户编号</param>
    /// <param name="password">密码</param>
    /// <returns></returns>
    public static int SysUser_UpdatePassword(int userid, string password)
    {
        string strSql = "update SysUser set [password]=@password where [userid]=@userid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@password",Utility.Encrypt(password)),
                                       new OleDbParameter("@userid",userid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 更新权限
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="userid">用户编号</param>
    /// <param name="mids">权限</param>
    /// <returns></returns>
    public static int SysUser_UpdateModuleid(int userid, string mids)
    {
        string strSql = "update SysUser set [moduleids]=@mids where [userid]=@userid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@mids",mids),
                                       new OleDbParameter("@userid",userid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="userid">用户编号</param>
    /// <returns></returns>
    public static int SysUser_Delete(string userid)
    {
        string strSql = "delete from [SysUser] where [userid]=@userid";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@userid",userid)
                                       };
        return SqlManage.GetInstance().ExecuteSql(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 用户登录验证
    /// </summary>
    /// <param name="sqlM"></param>
    /// <param name="username">用户名</param>
    /// <param name="password">用户密码</param>
    /// <returns></returns>
    public static object SysUser_Login(string username, string password)
    {
        string strSql = "select [username] from [SysUser] where [username]=@username and [password]=@password";

        OleDbParameter[] oleParams ={
                                       new OleDbParameter("@username",username),
                                       new OleDbParameter("@password",password)
                                       };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }

    /// <summary>
    /// 记录用户登录时间、ip
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    public static bool SysUser_UpdateUserInfo(string userName)
    {
        if (!string.IsNullOrEmpty(userName))
        {
            SqlManage sqlM = SqlManage.GetInstance();
            string strSql = "update [SysUser] set [lastlogintime]=@lastlogintime,[lastloginip]=@lastloginip where [username]=@username";
            OleDbParameter[] oleParams ={
                                        new OleDbParameter("@lastlogintime",DateTime.Now.ToString()),
                                        new OleDbParameter("@lastloginip",Utility.getLocalIP()),
                                        new OleDbParameter("@username",userName)
                                       };
            if (sqlM.ExecuteSql(CommandType.Text, strSql, oleParams) > 0)
                return true;
        }
        return false;
    }
    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns></returns>
    public static object SysUser_GetUserModule(string username)
    {
        string strSql = "select [moduleids] from [SysUser] where username=@username";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@username",username)
                                    };
        return SqlManage.GetInstance().GetFistColumn(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns></returns>
    public static DataSet SysUser_GetUserByUname(string username)
    {
        string strSql = "select * from [SysUser] where username=@username";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@username",username)
                                    };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 根据用户ID获取用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns></returns>
    public static DataSet SysUser_GetUserById(int id)
    {
        string strSql = "select * from [SysUser] where userid=@userid";

        OleDbParameter[] oleParams ={
                                        new OleDbParameter("@userid",id)
                                    };
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql, oleParams);
    }
    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="moduleid"></param>
    /// <returns></returns>
    public static DataSet SysUser_GetUsers()
    {
        string strSql = "select * from [SysUser] order by [addtime] desc";
        return SqlManage.GetInstance().GetDataSet(CommandType.Text, strSql);
    }
    #endregion
}

#endregion